import { useRequest } from "ahooks";

export const useHook = (props: {
  commitFn: (params: any) => Promise<any>; // 提交函数
  pollingFn: (requestId: string) => Promise<any>; // 轮询函数
  setLoading: (loading: boolean) => void;
  successCallback: (data: any) => void; // 成功回调
}) => {
  const { commitFn, pollingFn, successCallback } = props;

  // 轮询任务
  const getPollingData = async (
    requestId: string,
    success: (data: any) => void
  ) => {
    const data = await pollingFn(requestId);
    // 这里最好是统一返回值结构，如果不统一，这里还需要修改
    if (data === null) {
      // 如果任务未完成，继续轮询
      // todo: 优化轮询逻辑
    } else {
      // 如果任务完成，停止轮询
      success(data);
      cancel();
    }
  };

  const { run: getPollingDataRun, cancel } = useRequest(getPollingData, {
    pollingInterval: 2000, // 2s 轮询一次
    pollingWhenHidden: false, // 页面隐藏时停止轮询
    manual: true,
  });

  // 使用 useRequest 调用请求函数
  const { run: commitRun } = useRequest(commitFn, {
    manual: true, // 手动触发请求
    onSuccess: (result: string) => {
      getPollingDataRun(result, successCallback);
    },
  });
  return { commitRun, getPollingDataRun };
};
